const async = require('async');
const mysql = require('../../utils/db').mysql;
const md5 = require('md5');
exports.page = function(req, res, next){
    const userInfo = req.session.userInfo;
    if(userInfo.userType != 1){
        res.status = 404;
        res.send('404');
        return;
    }
    req.session.touch();
    res.render('admin/addUser', {
        userInfo: userInfo,
        channel: {
            type: 'manage-user',
            index: 1
        }
    });
}
exports.addUser = function(req, res, next){
    const userInfo = req.session.userInfo;
    if(!req.body.username || !req.body.passwd){
        res.send({
            code: 500,
            msg: '请提交完整表单'
        });
        return;
    }
    if(!userInfo.userType || userInfo.userType != 1){
        res.send({
            code: 400,
            msg: '没有权限'
        });
        return;
    }
    const passwd = md5(req.body.passwd);
    const data = {
        username: req.body.username,
        passwd: passwd,
        usertype: req.body.usertype || 2,
        createtime: new Date(),
        newsAuthority: req.body.newsAuthority || 2
    }
    const queryStr = 'INSERT INTO adminuser (username, passwd, usertype, createtime, newsAuthority) VALUES (?,?,?,?,?)';
    const queryArr = [data.username, data.passwd, data.usertype, data.createtime, data.newsAuthority];
    mysql.getConnection(function(err, conn) {
        conn.query(queryStr, queryArr, function (err, results) {
            if (err) {
                console.log('Error:' + err, '========addUser=======');
                res.send({
                    code: 400,
                    msg: '添加用户失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加用户成功'
                });
            };
            mysql.releaseConnection(conn);
        });
    })
}